<template>
  <!-- 【模版】参数 弹窗 -->
  <a-modal
    v-model:open="visible"
    :title="`${rowData.modelName}参数`"
    @ok="handleOk"
    destroyOnClose
    :width="1300"
    @cancel="cancel"
    :footer="null"
    centered
  >
    <div class="filterContent">
      <a-form :model="filterForm" layout="inline">
        <a-form-item label="模版参数名称：" name="name">
          <a-input
            v-model:value="filterForm.name"
            placeholder="请输入"
            allow-clear
          />
        </a-form-item>
        <a-form-item label="模版属性名称：" name="attrName">
          <a-input
            v-model:value="filterForm.attrName"
            placeholder="请输入"
            allow-clear
          />
        </a-form-item>
        <a-form-item label="是否启用：">
          <a-select
            v-model:value="filterForm.enable"
            class="formSelect"
            placeholder="请选择"
            allow-clear
          >
            <a-select-option
              v-for="item in MODEL_PARAMS_STATUS_LIST"
              :value="item.value"
              :key="item.value"
            >
              {{ item.label }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-button type="primary" class="filterBtn" @click="getModelParamPage"
          >查询</a-button
        >
        <a-button type="primary" class="filterBtn greenBtn" @click="handleParam"
          >新增</a-button
        >
        <a-upload
          v-model:file-list="fileList"
          class="upLoad"
          accept=".xlsx,.xls,.csv"
          :showUploadList="false"
          :maxCount="1"
          :action="handleImport"
          :beforeUpload="beforeUpload"
          :data="{
            modelId: rowData.id,
          }"
          :headers="headers"
          ref="uploadRef"
          @change="handleUploadChange"
        >
          <a-button type="warning" class="filterBtn yellowBtn"
            >导入参数</a-button
          >
        </a-upload>

        <a-button class="filterBtn" @click="handleDownload">模版下载</a-button>
      </a-form>
    </div>
    <div class="tableContent">
      <a-table
        :dataSource="tableData"
        :columns="columns"
        size="small"
        :scroll="{ x: 'max-content' }"
        @resizeColumn="handleResizeColumn"
        :pagination="false"
        :loading="tableLoading"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'paramType'">
            {{
              PARAM_TYPE.filter((item) => item.value === record.paramType)[0]
                ?.label
            }}
          </template>
          <template v-if="column.key === 'dataType'">
            {{ DATA_TYPE.filter((item) => item.value === record.dataType)[0]
                ?.label }}
          </template>
          <template v-if="column.key === 'storageType'">
            {{ modelStorageList.filter((item) => item.value === record.storageType)[0]
                ?.label }}
          </template>
          <template v-if="column.key === 'dataRule'">
            {{ DATA_RULE.filter((item) => item.value === record.dataRule)[0]
                ?.label }}
          </template>
          <template v-if="column.key === 'evtType'">
            {{ EVT_TYPE.filter((item) => item.value === record.evtType)[0]
                ?.label }}
          </template>
          <template v-if="column.key === 'evtRule'">
            {{ EVT_RULE.filter((item) => item.value === record.evtRule)[0]
                ?.label }}
          </template>

          <template v-if="column.key === 'enable'">
            {{ MODEL_PARAMS_STATUS_LIST.filter((item) => item.value === record.enable)[0]
                ?.label }}
          </template>
          <template v-if="column.key === 'handle'">
            <a-popconfirm
              ok-text="确认"
              cancel-text="取消"
              @confirm="confirmDel(record)"
            >
              <template #title> 确定删除该条参数数据？ </template>
              <a-button type="link" danger>删除</a-button>
            </a-popconfirm>
            <a-button type="link" @click="handleEdit(record)">编辑</a-button>
            <a-popconfirm
              ok-text="确认"
              cancel-text="取消"
              @confirm="handleModelStatus(record)"
            >
              <template #title>
                {{
                  `是否确定${record.enable === 1 ? "停用" : "启用"}该条数据？`
                }}
              </template>
              <a-button type="link" danger>
                {{ record.enable === 1 ? "停用" : "启用" }}
              </a-button>
            </a-popconfirm>
          </template>
        </template>
      </a-table>
    </div>
    <a-pagination
      v-model:current="filterForm.current"
      v-model:page-size="filterForm.size"
      :total="total"
      position="bottomRight"
      show-size-changer
      @change="getModelParamPage"
      :show-total="(total) => `总共 ${total} 条`"
    >
      <template #buildOptionText="props">
        <span>{{ props.value }}条/页</span>
      </template>
    </a-pagination>

    <!-- 新增参数 -->
    <AddParam
      :addParamVisible="addParamVisible"
      :rowData="rowData"
      :paramRowData="paramRowData"
      :isEdit="isEdit"
      :modelStorageList="modelStorageList"
      @update:addParamVisible="addParamVisible = $event"
      @getModelParamPage="getModelParamPage"
    />
  </a-modal>
</template>
<script setup>

import AddParam from "./addParam.vue";
import storage from "@/utils/storage"
import {
  MODEL_PARAMS_STATUS_LIST,
  PARAM_TYPE,
  DATA_TYPE,
  DATA_RULE,
  EVT_RULE,
  EVT_TYPE,
} from "@/constants/stationConfig";

const $api = inject("$api");
const props = defineProps({
  tempDataVisible: {
    type: Boolean,
    default: false,
  },
  rowData: {
    type: Object,
  },
});
const fileList = ref([]);
const visible = ref(props.tempDataVisible);
const userInf = storage.getItem("USER_INFO")
const headers = ref({
  Authorization: "Bearer " + userInf.access_token,
})
const addParamVisible = ref(false);
const emits = defineEmits(["update:tempDataVisible"]);
watch(
  () => props.tempDataVisible,
  (val) => {
    visible.value = val;
    if (val) {
      getModelParamPage();
    }
  }
);
const labelCol = { style: { width: "130px" } };
const total = ref();
const filterForm = ref({
  name: undefined,
  attrName: undefined,
  enable: undefined,
  current: 1,
  size: 10,
});
const tableData = ref([]);
const isEdit = ref(false);
const columns = ref([
  {
    title: "模版参数名称",
    dataIndex: "name",
    key: "name",
    width: 200,
    resizable: true,
    align: "center",
    class: "nameCol",
  },
  {
    title: "模版属性名称",
    dataIndex: "attrName",
    key: "attrName",
    width: 200,
    resizable: true,
    align: "center",
  },
  {
    title: "描述",
    dataIndex: "paramDesc",
    key: "paramDesc",
    resizable: true,
    align: "center",
  },
  {
    title: "参数类别",
    dataIndex: "paramType",
    key: "paramType",
    width: 180,
    resizable: true,
    align: "center",
  },
  {
    title: "初始值",
    dataIndex: "initValue",
    key: "initValue",
    width: 120,
    resizable: true,
    align: "center",
  },
  {
    title: "计算公式",
    dataIndex: "calcFormula",
    key: "calcFormula",
    width: 120,
    resizable: true,
    align: "center",
  },
  {
    title: "数据类别",
    dataIndex: "dataType",
    key: "dataType",
    width: 120,
    resizable: true,
    align: "center",
  },
  {
    title: "单位",
    dataIndex: "unit",
    key: "unit",
    width: 120,
    resizable: true,
    align: "center",
  },
  {
    title: "报文类别",
    dataIndex: "msgCode",
    key: "msgCode",
    width: 120,
    resizable: true,
    align: "center",
  },
  {
    title: "存储类型",
    dataIndex: "storageType",
    key: "storageType",
    width: 180,
    resizable: true,
    align: "center",
  },
  {
    title: "数据间隔时长",
    dataIndex: "hisInterval",
    key: "hisInterval",
    width: 120,
    resizable: true,
    align: "center",
  },
  {
    title: "告警规则",
    dataIndex: "evtRule",
    key: "evtRule",
    width: 120,
    resizable: true,
    align: "center",
  },
  {
    title: "告警类别",
    dataIndex: "evtType",
    key: "evtType",
    width: 120,
    resizable: true,
    align: "center",
  },
  {
    title: "小数位",
    dataIndex: "scale",
    key: "scale",
    width: 120,
    resizable: true,
    align: "center",
  },
  {
    title: "状态",
    dataIndex: "enable",
    key: "enable",
    width: 120,
    resizable: true,
    align: "center",
  },
  {
    title: "操作",
    dataIndex: "handle",
    key: "handle",
    width: 150,
    resizable: true,
    align: "center",
    fixed: "right",
  },
]);
const cancel = () => {
  emits("update:tempDataVisible", false);
  filterForm.value = {
    name: undefined,
    attrName: undefined,
    enable: undefined,
    current: 1,
    size: 10,
  };
};
const confirmDel = async (data) => {
  const res = await $api.modelParamDel(data.id);
  if (res && res.code === 0) {
    message.success("删除成功");
    getModelParamPage();
  }
};
const paramRowData = ref({});
const handleParam = () => {
  addParamVisible.value = true;
  paramRowData.value = {};
  isEdit.value = false;
};
const handleEdit = (data) => {
  paramRowData.value = data;
  addParamVisible.value = true;
  isEdit.value = true;
};
const tableLoading = ref(false);
const getModelParamPage = async () => {
  const params = {
    ...filterForm.value,
    modelId: props.rowData.id,
  };
  tableLoading.value = true;
  const res = await $api.modelParamPage(params);
  tableLoading.value = false;
  tableData.value = [...res.data.records];
  total.value = res.data.total;
};
const handleModelStatus = async (data) => {
  const res = await $api.updateModelParamStatus({
    id: data.id,
    enable: data.enable === 1 ? 0 : 1, // 如果启用则停用，如果停用或未启用，则启用
  });
  if (res && res.code === 0) {
    message.success("操作成功");
    getModelParamPage();
  }
};
const handleDownload = async () => {
  window.open(
    `https://ngp-cloud.oss-cn-shenzhen.aliyuncs.com/public/monitor/%E7%A4%BA%E4%BE%8B%E6%96%87%E4%BB%B6-%E6%A8%A1%E6%9D%BF%E5%8F%82%E6%95%B0-250116.xlsx`
  );
};
// 导入
const handleImport = async (val) => {
  return "/api/monitor/modelParam/import";
};
const handleUploadChange = (data) => {
  const { file } = data;
  if (file.status === "done") {
    message.success("导入成功");
    getModelParamPage();
  } else if (file.response) {
    message.error(`导入失败：${file.response?.msg}`);
  }
};
const modelStorageList = ref([]);
const getModelStorageList = async () => {
  const res = await $api.modelStorageList();
  if (res && res.code === 0) {
    for (const key in res.data) {
      modelStorageList.value.push({
        value: Number(key),
        label: res.data[key], 
      });
    }
  }
};
onMounted(() => {
  getModelStorageList();
});
</script>

<style lang="less" scoped>
.ant-table {
  .ant-btn {
    padding: 4px 5px;
  }
}
.tableContent {
  border-radius: 4px;
  background-color: #141414;
  padding: 8px;
}
.filterContent {
  background: none;
}
.filterBtn {
  margin: 0 20px 20px 0;
  &:last-child {
    margin-right: 0;
  }
}
.formSelect {
  width: 120px;
}
.upLoad {
  margin-right: 20px;
}
</style>